﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using App.Data;
using App.Core.Extensions;
using System.IO;
using System.Web.Services;
using App.Core.Mail;


public partial class Pages_Public_ProjectDetails : BasePage
{
    protected int _ProjectID;    
    protected ProjectFile _ProjectFile = null;
    protected String _Latitude = String.Empty;
    protected String _Longitude = String.Empty;
    protected String _GoogleMapMessage = String.Empty;

    protected void Page_Load(object sender, EventArgs e)
    {
        BindPageInfo();
        if (!IsPostBack)
        {
            BindProjectDeatils();
            App.Core.Mail.MailManager.SmtpHost = ConfigReader.SmtpHost;
            App.Core.Mail.MailManager.SmtpPort = ConfigReader.SmtpPort;
        }
    }
    protected void BindPageInfo()
    {
        _ProjectID = WebUtil.GetQueryStringInInt(AppConstants.QueryString.ID);
        Page.Title = WebUtil.GetPageTitle("Project Details");
    }
    protected void BindProjectDeatils()
    {
        BtcHousingEntities context = new BtcHousingEntities();
        Project project = context.Projects.FirstOrDefault(P => P.ID == _ProjectID);        
        //_ProjectFile = project.ProjectFiles.FirstOrDefault(P => P.FileTypeID != ConfigReader.ProjectBrocheureFileTypeID);        
        if (project == null)
            ShowNotFoundMessage();
        else
        {
            if (!project.IsApproved)
                ShowNotFoundMessage();
            else
            {
                h4Heading.InnerHtml = project.Name.HtmlEncode();
                ltrProjectTitle.Text = project.Name.HtmlEncode();
                BindProjectImages(context, project);
                String table = @"<table cellpadding='3' cellspacing='0' style='width:100%;'>
                                <colgroup>
                                    <col style='width:20%;' />
                                    <col />
                                </colgroup>
                                {0}
                            </table>";
                StringBuilder sb = new StringBuilder();
                ///Bind General Information
                sb.AppendFormat("<tr><td>Project Name</td> <td>{0}</td></tr>", project.Name.HtmlEncode());
                sb.AppendFormat("<tr><td>Company</td> <td><a href='{0}?{1}={2}'>{3}</a></td></tr>"
                    , AppConstants.Pages.COMPANY_PROFILE
                    , AppConstants.QueryString.ID, project.CustomerID
                    , project.Customer.Name.HtmlEncode());
                sb.AppendFormat("<tr><td>Status</td> <td>{0}</td></tr>", project.ProjectStatus.Name);
                sb.AppendFormat("<tr><td>Description</td> <td>{0}</td></tr>", WebUtil.FormatText(project.Description));

                ltrGeneralInformation.Text = String.Format(table, sb.ToString());
                sb.Length = 0;

                ///Bind Location
                String locationTable = @"<table cellpadding='3' cellspacing='0' style='width:100%;'>
                                        <colgroup>
                                            <col style='width:20%;' />
                                            <col />
                                            <col style='width:100px;' />
                                        </colgroup>
                                        {0}
                                    </table>";
                sb.AppendFormat("<tr><td>Country</td> <td>{0}</td><td><a href='javascript:void(0);' onclick='ShowLocationInGoogleMap();'>View In Map</a></td></tr>", project.Zone.City.Country.Name.HtmlEncode());
                sb.AppendFormat("<tr><td>City</td> <td colspan='2'>{0}</td></tr>", project.Zone.City.Name.HtmlEncode());
                sb.AppendFormat("<tr><td>Zone</td> <td colspan='2'>{0}</td></tr>", project.Zone.Name.HtmlEncode());

                if (!project.StreetAddress.IsNullOrEmpty())
                    sb.AppendFormat("<tr><td>Street Address</td> <td colspan='2'>{0}</td></tr>", project.StreetAddress.HtmlEncode());
                if (!project.HouseNo.IsNullOrEmpty())
                    sb.AppendFormat("<tr><td>House</td> <td colspan='2'>{0}</td></tr>", project.HouseNo.HtmlEncode());
                if (!project.AddressHint.IsNullOrEmpty())
                    sb.AppendFormat("<tr><td>Address Hint</td> <td colspan='2'>{0}</td></tr>", WebUtil.FormatText(project.AddressHint));
                ltrLocation.Text = String.Format(locationTable, sb.ToString());
                sb.Length = 0;

                ///Bind Specifications
                sb.AppendFormat("<tr><td>Size ({0})</td> <td>{1}</td></tr>", project.Unit.Name, GetSize(project));

                if (!project.AreaOther.IsNullOrEmpty())
                    sb.AppendFormat("<tr><td>Other Aavailable Sizes</td> <td>{0}</td></tr>", project.AreaOther.HtmlEncode());

                if (project.PropertyTypeID != ConfigReader.LandPropertyTypeID)
                {
                    sb.AppendFormat("<tr><td>Number Of Units</td> <td>{0}</td></tr>", project.NoOfUnits);
                    sb.AppendFormat("<tr><td>Number of Beds</td> <td>{0}</td></tr>", project.NoOfBeds);
                    sb.AppendFormat("<tr><td>Number Of Floors</td> <td>{0}</td></tr>", project.NoOfFloors);
                    sb.AppendFormat("<tr><td>Available Units</td> <td>{0}</td></tr>", project.AvailableUnits);

                    sb.AppendFormat("<tr><td>Has Parking?</td> <td>{0}</td></tr>", project.HasParking ? "Yes" : "No");
                    sb.AppendFormat("<tr><td>Has Generator?</td> <td>{0}</td></tr>", project.HasGenerator ? "Yes" : "No");
                    sb.AppendFormat("<tr><td>Has Lift?</td> <td>{0}</td></tr>", project.HasLift ? "Yes" : "No");
                    sb.AppendFormat("<tr><td>Has Security?</td> <td>{0}</td></tr>", project.HasSecurity ? "Yes" : "No");
                }
                ltrSpecification.Text = String.Format(table, sb.ToString());
                sb.Length = 0;

                ///Bind pricing
                if (project.PricePerUnitFrom > 0 && project.PricePerUnitTo > 0 & project.ShowPricingInfo)
                    sb.AppendFormat("<tr><td>Price Per {0}</td> <td>From {1} To {2}</td></tr>", project.Unit.Name, WebUtil.FormatData(project.PricePerUnitFrom), WebUtil.FormatData(project.PricePerUnitTo));
                else
                    sb.AppendFormat("<tr><td>Price Per {0}</td> <td>Negotiatable</td></tr>", project.Unit.Name);
                sb.AppendFormat("<tr><td>Booking Price</td> <td>{0}</td></tr>", project.BookingFee.IsNullOrEmpty() ? "Negotiatable" : WebUtil.FormatData(project.BookingFee));
                sb.AppendFormat("<tr><td>Booking Available?</td> <td>{0}</td></tr>", project.HasBookingAvailable ? "Yes" : "No");
                ltrPricing.Text = String.Format(table, sb.ToString());
                sb.Length = 0;

                ///Bind Contact person
                if (IsIndividual)
                {
                    foreach (ProjectContact projectContact in project.ProjectContacts)
                    {
                        sb.AppendFormat("<tr><td>Name</td> <td>{0}</td></tr>", projectContact.Contact.Name.HtmlEncode());
                        sb.AppendFormat("<tr><td>Email</td> <td>{0}</td></tr>", projectContact.Contact.Email.HtmlEncode());
                        if (!projectContact.Contact.Phone.IsNullOrEmpty())
                            sb.AppendFormat("<tr><td>Phone</td> <td>{0}</td></tr>", projectContact.Contact.Phone.HtmlEncode());
                    }
                }
                else
                {
                    sb.AppendFormat(@"<tr>
                                    <td colspan='2'>Please Login as Individual to view contact information and other options.
                                     <a href='{0}'>Click Here</a> to Login   </td>
                                  </tr>", WebUtil.BuildLoginUrl(String.Format("{0}{1}", Request.Url.AbsolutePath, WebUtil.BuildUrlWithQueryStrings())));
                }
                ltrContactPerson.Text = String.Format(table, sb.ToString());

                BindGoogleMap(project);
            }
        }
    }

    protected String GetSize(Project project)
    {
        if (project.AreaTo.GetValueOrDefault() > 0)
            return String.Format("From {0} To {1}", WebUtil.FormatData(project.Area), WebUtil.FormatData(project.AreaTo));
        return WebUtil.FormatData(project.Area);
    } 

    protected void BindProjectImages(BtcHousingEntities context, Project project)
    {
        String html = @"<div class='ThumbContainer'>
                            <img src='{0}/{1}/{2}' LargeImage='{0}/{1}/{3}' title='Click to View Large' alt='Click to View Large' style='cursor:pointer;' onclick='ShowLargeImage(this);' />                            
                        </div>";
        //var projectFiles = project.ProjectFiles.Where(P => P.FileTypeID != ConfigReader.BrocheureFileTypeID);

        var projectFiles = from P in context.ProjectFiles where P.ProjectID == project.ID && P.FileTypeID != ConfigReader.BrocheureFileTypeID select P;
        if (projectFiles != null && projectFiles.Count() > 0)
        {
            StringBuilder sb = new StringBuilder();
            foreach (ProjectFile image in projectFiles)
            {
                sb.AppendFormat(html, AppConstants.PROJECT_FILES, project.ID, image.ThumbFileName, image.FileName);
            }
            ltrProjectFiles.Text = sb.ToString();
        }
        var brocheure = project.ProjectFiles.FirstOrDefault(P => P.FileTypeID == ConfigReader.BrocheureFileTypeID);
        if (brocheure != null)
        {
            //hplBrocheure.NavigateUrl = String.Format("{0}/{1}/{2}", AppConstants.PROJECT_FILES, project.ID, brocheure.FileName);
            //hplBrocheure.Visible = true;
            anchorBrocheure.Attributes["href"] = String.Format("{0}/{1}/{2}", AppConstants.PROJECT_FILES, project.ID, brocheure.FileName);
            divDownloadBrocheure.Visible = true;
        }
        if (SessionCache.CurrentUser != null)
        {
            //hplSendToFriend.NavigateUrl = String.Format("javascript:void(0);");
            //hplSendToFriend.Attributes["onclick"] = "SendToFriend();";
            //hplSendToFriend.Visible = true;

            //hplAddToFavorite.NavigateUrl = String.Format("javascript:void(0);");
            //hplAddToFavorite.Attributes["onclick"] = "AddToFavorite();";
            //hplAddToFavorite.Visible = true;
            divAddToFavorite.Visible = true;
            if(SessionCache.CurrentUser.GroupID == ConfigReader.IndividualUserGroupID)
                divSendToFriend.Visible = true;
        }
    }
    protected void BindGoogleMap(Project project)
    {
        //String url = String.Format("http://maps.google.com/maps?file=api&v=2&sensor=false&key={0}", ConfigReader.GoogleMapsAPIKey);
        StringBuilder sb = new StringBuilder(10);
        String streetAddress = GetStreetAddress(project);
        sb.AppendFormat("{0}{1}, {2}, {3}", streetAddress, project.Zone.Name.UrlEncode(), project.Zone.City.Name.UrlEncode(), project.Zone.City.Country.Name.UrlEncode());
        String geoLocationURL = String.Format(ConfigReader.GoogleGeoLocationURL, sb.ToString());
        try
        {
            String xml = WebUtil.MakeWebRequest(geoLocationURL);
            ///Deserilize the XML
            System.IO.StringReader stringReader = new System.IO.StringReader(xml);
            System.Xml.XmlTextReader xmlReader = new System.Xml.XmlTextReader(stringReader);
            //System.IO.StreamReader stream = new System.IO.StreamReader(destination);
            System.Xml.Serialization.XmlSerializer xmlSerilizer = new System.Xml.Serialization.XmlSerializer(typeof(GeocodeResponse));
            GeocodeResponse geoCode = xmlSerilizer.Deserialize(xmlReader) as GeocodeResponse;
            decimal latitude = geoCode.result.geometry.location.lat;
            decimal longitude = geoCode.result.geometry.location.lng;
            _Latitude = latitude.ToString();
            _Longitude = longitude.ToString();
        }
        catch
        {
            _GoogleMapMessage = "Unable to load google map for the given address.";
        }
    }

    private string GetStreetAddress(Project project)
    {
        StringBuilder sb = new StringBuilder();
        if(!project.StreetAddress.IsNullOrEmpty())
            sb.AppendFormat(project.StreetAddress.Trim());
        if(!project.HouseNo.IsNullOrEmpty())
            sb.AppendFormat(project.HouseNo);
        if (sb.Length > 0)
            sb.AppendFormat(", ");
        return sb.ToString().UrlEncode();
    }
    protected void ShowNotFoundMessage()
    {
        WebUtil.ShowMessageBox(divMessage, "Requested Project was not found.", true);
        pnlFormContainer.Visible = false;
    }

    [WebMethod(EnableSession = true)]
    public static bool SendEmailToFriend(int projectID, String toName, String toEmail, String message)
    {
        BtcHousingEntities context = new BtcHousingEntities();
        var project = context.Projects.FirstOrDefault(P => P.ID == projectID);
        if (project != null)
        {
            StringBuilder emailTemplate = new StringBuilder(WebUtil.ReadEmailTemplate(AppConstants.EmailTemplate.COMMON));
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("Dear {0},<br/>", toName.HtmlEncode());
            sb.AppendFormat("Your friend sent you the following project from {0}. Click on the link below to take a look at it.<br /><br />", ConfigReader.ProviderCompany);
            sb.AppendFormat("<a href='{0}{1}?{2}={3}'>{0}{1}?{2}={3}</a>", WebUtil.GetDomainAddress(), 
                AppConstants.Pages.PROJECT_DETAILS
                , AppConstants.QueryString.ID, project.ID);
            sb.AppendFormat("<br/><br/><b>Message from Your Friend:</b><br/>{0}", WebUtil.FormatText(message));

            emailTemplate.Replace(AppConstants.ETConstants.DOMAIN, WebUtil.GetDomainAddress());
            emailTemplate.Replace(AppConstants.ETConstants.MESSAGE, sb.ToString());
            String subject = String.Format("Your friend sent you a project from {0}", ConfigReader.ProviderCompany);
            try
            {
                MailManager.SendMail(toEmail, String.Empty, String.Empty, SessionCache.CurrentUser.LoginName, subject, emailTemplate.ToString());
                return true;
            }
            catch
            {
                //BtcHousingEntities context = new BtcHousingEntities();
                EmailMessage failedMessage = new EmailMessage();
                failedMessage.Subject = subject;
                failedMessage.FromEmail = SessionCache.CurrentUser.LoginName;
                failedMessage.ToEmail = toEmail;
                failedMessage.Message = emailTemplate.ToString();
                failedMessage.IsSent = false;
                failedMessage.Created = DateTime.Now;
                failedMessage.AttemptedOn = DateTime.Now;
                context.AddToEmailMessages(failedMessage);
                context.SaveChanges();
            }
        }
        return false;
    }
    [WebMethod (EnableSession=true)]
    public static bool AddToFavorite(int projectID)
    {
        BtcHousingEntities context = new BtcHousingEntities();
        var project = context.Projects.FirstOrDefault(P => P.ID == projectID);
        if (project != null)
        {
            var existingFavorites = from P in context.Favorites where P.UserID == SessionCache.CurrentUser.ID && P.ProjectID == projectID select P;
            if (existingFavorites == null || existingFavorites.Count() == 0)
            {
                Favorite favorite = new Favorite();
                favorite.UserID = SessionCache.CurrentUser.ID;
                favorite.Created = DateTime.Now;
                project.Favorites.Add(favorite);
                context.SaveChanges();
            }
            return true;
        }
        return false;
    }
}